package com.dyh.quickdemozwei.d1216;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author: yhdong
 * @Date: 2021/12/16 16:03
 */

@Slf4j
public class TestCFutrue {

    List<String> datas = Lists.newArrayList(
        "fo",
        "bar",
        "banana",
        "hello"
    );

    public Integer s1(String data)   {
        log.info("data={}",data);
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return data.length();
    }

//    ExecutorService poolExecutor = Executors.newCachedThreadPool();
    ExecutorService poolExecutor = Executors.newFixedThreadPool(10);

    @Test
    public void test() throws InterruptedException {

        List<CompletableFuture<Integer> > s1Futures = datas.stream().map(
//                e->CompletableFuture.supplyAsync(()->s1(e))
                e->CompletableFuture.supplyAsync(()->s1(e),poolExecutor)
        ).collect(Collectors.toList());

        CompletableFuture<List<Integer>> allS1DoneFuture = CompletableFuture
                .allOf(s1Futures.toArray(new CompletableFuture[0]))
                .thenApply( e->s1Futures.stream().map(CompletableFuture::join).collect(Collectors.toList()) )
                ;

        CompletableFuture afterAll = allS1DoneFuture.thenAccept(
             e->{
                 for (Integer integer : e) {
                     log.info("{} lenth={}",Thread.currentThread().getName(),integer);
                     if (integer==5)
                         throw new RuntimeException("testRt");
                 }
             }
        );


       Thread t =  new Thread(
                ()->{
                    try {
                        afterAll.join();
                    }catch (Exception e){
                        log.info("ex =",e);
                    }

                }
        );
       t.start();

       t.join();
//        try {
//            afterAll.join();
//        } catch (Exception e) {
//
//            System.out.println();
//        }
    }
}
